/**
 * \file Server.cc
 * \brief Display server
 * \author Corey Tabaka
 */

/*
   Copyright 2007 Corey Tabaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <Server.h>

HandleMap<RefResource> Resource::resources;

Resource::Resource(int _id, int _type) : id(_id), type(_type), self(this, true)
{
}

int Resource::getId(void) {
	return id;
}

void Resource::add(RefResource res) {
	resources.put(res->getId(), res);
}

void Resource::remove(RefResource res) {
	resources.remove(res->getId());
}

bool Resource::contains(int id) {
	return resources.containsHandle(id);
}

ImageBuffer::ImageBuffer(uint8 *buffer, int width, int height, int scan) :
	buf(buffer, width, height, scan), pixf(buf), ren(pixf) {
}

ImageBuffer::ImageBuffer(ImageBuffer &ib, int x, int y, int width, int height) {
	init(ib, x, y, width, height);
}

ImageBuffer::ImageBuffer(ImageBuffer &ib, agg::rect_i box) {
	init(ib, box);
}

ImageBuffer::ImageBuffer(const ImageBuffer &ib) :
	buf((uint8 *) ib.buf.buf(), ib.buf.width(), ib.buf.height(),
	ib.buf.stride()), pixf(buf), ren(pixf) {
}

void ImageBuffer::init(uint8 *buffer, int width, int height, int scan) {
	buf.attach(buffer, width, height, scan);
	ren.reset_clipping(true);
}

void ImageBuffer::init(ImageBuffer &ib, int x, int y, int width, int height) {
	agg::rect_i rect(x, y, x + width - 1, y + height - 1);
	agg::rect_i bounds(0, 0, ib.buf.width() - 1, ib.buf.height() - 1);
	
	bounds = intersect_rectangles(rect, bounds);
	
	// ImageBuffer assumes 4 bytes per pixel
	uint8 *buffer = ib.buf.buf() + bounds.y1 * ib.buf.stride() + bounds.x1 * 4;
	buf.attach(buffer, bounds.x2 - bounds.x1 + 1, bounds.y2 - bounds.y1 + 1,
		ib.buf.stride());
	ren.reset_clipping(true);
}

void ImageBuffer::init(ImageBuffer &ib, agg::rect_i box) {
	agg::rect_i bounds(0, 0, ib.buf.width() - 1, ib.buf.height() - 1);
	
	bounds = intersect_rectangles(box, bounds);
	
	// ImageBuffer assumes 4 bytes per pixel
	uint8 *buffer = ib.buf.buf() + bounds.y1 * ib.buf.stride() + bounds.x1 * 4;
	buf.attach(buffer, bounds.x2 - bounds.x1 + 1, bounds.y2 - bounds.y1 + 1,
		ib.buf.stride());
	ren.reset_clipping(true);
}

Cursor::Cursor(int id, ImageBuffer &ib, int hx, int hy) :
	Resource(id, RESOURCE_TYPE_CURSOR), image(ib), hotX(hx), hotY(hy) {
}
